<template>
  <el-form label-width="100px">

    <el-form-item label="SPU名称">
      {{ spuInfo.spuName }}
    </el-form-item>

    <el-form-item label="SKU名称">
      <el-input v-model="skuForm.skuName" placeholder="SKU名称"></el-input>
    </el-form-item>

    <el-form-item label="价格(元)">
      <el-input type="number" v-model="skuForm.price" placeholder="价格(元)"></el-input>
    </el-form-item>

    <el-form-item label="重量(千克)">
      <el-input type="number" v-model="skuForm.weight" placeholder="重量(千克)"></el-input>
    </el-form-item>

    <el-form-item label="规格描述">
      <el-input type="textarea" v-model="skuForm.skuDesc" :rows="3" placeholder="规格描述"></el-input>
    </el-form-item>


    <el-form-item label="平台属性">

      <el-form :inline="true">
        <el-form-item v-for="attr in attrList" :key="attr.id" :label="attr.attrName">
          <el-select 
            placeholder="请选择"
            v-model="attr.attrIdvalId"
          >
            <el-option 
              v-for="attrVal in attr.attrValueList" :key="attrVal.id" 
              :label="attrVal.valueName"
              :value="`${attr.id}:${attrVal.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

    </el-form-item>


    <el-form-item label="销售属性">
      <el-form :inline="true">
        <el-form-item v-for="saleAttr in saleAttrList" :key="saleAttr.id" :label="saleAttr.saleAttrName">
          <el-select 
            v-model="saleAttr.attrIdvalId"
            placeholder="请选择"
          >
            <el-option 
              v-for="saleAttrVal in saleAttr.spuSaleAttrValueList" 
              :key="saleAttrVal.id"
              :label="saleAttrVal.saleAttrValueName" :value="`${saleAttr.id}:${saleAttrVal.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>


    <el-form-item label="图片列表">
      <el-table :data="spuImageList" border @selection-change="selectionChange" size="small">
        <el-table-column type="selection" width="80" align="center"></el-table-column>
        <el-table-column label="图片">
          <template #default="{ row, $index }">
            <img :src="row.imgUrl" style="width: 60px;height: 60px;">
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row, $index }">
            <el-tag type="success" v-if="row.isDefault == '1'">默认</el-tag>
            <el-button v-else @click="setDefaultImage(row)" type="primary" size="small">设为默认</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>


    <el-form-item>
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-button @click="cancelSave">取消</el-button>
    </el-form-item>

  </el-form>



</template>

<script setup lang="ts">
import attrApi, { type AttrModel } from '@/api/attr';
import skuApi,  {type SkuModel } from '@/api/sku';
import spuApi, { type SpuImageModel, type SpuModel, type SpuSaleAttrModel } from '@/api/spu';
import useCategoryStore from '@/stores/category';
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import { STATUS } from '../../index.vue'

const categoryStore = useCategoryStore()

const props = defineProps<{
  modelValue: number,
  spuInfo: SpuModel
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', status: number): void
  (e: 'changeSpuInfo'): void
}>()


// 保存的回调
const onSave = async () => { 
  // console.log('平台属性 -> ', attrList.value.filter(item => item.attrIdvalId) )
  // console.log('销售属性 -> ', saleAttrList.value.filter(item => item.attrIdvalId) )

  // 组装数据
  // 组装平台属性数据
  skuForm.value.skuAttrValueList = attrList.value.filter(item=>item.attrIdvalId).map(item=>{
    const [attrId,valueId] = item.attrIdvalId!.split(':')
    return {
      attrId,
      valueId
    }
  })

  // 组装销售属性
  skuForm.value.skuSaleAttrValueList = saleAttrList.value.filter(item=>item.attrIdvalId).map(item=>{
    const [saleAttrId,saleAttrValueId] = item.attrIdvalId!.split(':')
    return {
      saleAttrId,
      saleAttrValueId
    }
  })
  
  // 默认图片
  skuForm.value.skuDefaultImg = (spuImageList.value.find(item=>item.isDefault == '1' )|| {}).imgUrl!

  skuForm.value.spuId = props.spuInfo.id;
  skuForm.value.tmId = props.spuInfo.tmId;
  skuForm.value.category3Id = props.spuInfo.category3Id
  // price,skuName,skuDesc,weight  v-model 收集

  // 调用接口
  try {
    await skuApi.save(skuForm.value)
    ElMessage.success('保存成功')
    cancelSave()
  } catch (error) {
    
  }
}

// 取消保存的回调
const cancelSave = ()=>{
  emit('update:modelValue', STATUS.SPULIST)
  // 切换主列表
  // 同时需要初始化一下 父组件的spuInfo,防止再次新增 spu 会把 spuInfo 的数据传入 spuForm
  emit('changeSpuInfo')
}



// 图片表格选中的回调
const selectionChange = (val: any) => {
  // console.log('图片选中参数', val)
  skuForm.value.skuImageList = val
}
// 设置默认图片
const setDefaultImage = (row:SpuImageModel)=>{
  spuImageList.value.forEach(item=>item.isDefault = '0')
  row.isDefault = '1'
}


// 初始化 skuForm
const initSkuForm = (): SkuModel => ({
  spuId: undefined,
  price: undefined,
  skuName: '',
  skuDesc: '',
  weight: '',
  tmId: undefined,
  category3Id: undefined,
  skuDefaultImg: '', // 默认图片
  createTime: '',
  // 图片列表
  skuImageList: [],
  // 平台属性
  skuAttrValueList: [],
  // 销售属性
  skuSaleAttrValueList: []
})
// 收集数据
const skuForm = ref<SkuModel>(initSkuForm())





// 获取平台属性
const attrList = ref<AttrModel[]>([])
const getAttrList = async () => {
  try {
    const { category1Id, category2Id, category3Id } = categoryStore
    let result = await attrApi.attrInfoList(category1Id!, category2Id!, category3Id!)
    attrList.value = result
  } catch (error) {
    ElMessage.error('获取平台属性失败，请重试')
  }
}
// 获取销售属性列表
const saleAttrList = ref<SpuSaleAttrModel[]>([])
const getSaleAttrListBySkuId = async () => {
  try {

    let result = await spuApi.getSpuSaleAttrListBySpuId(props.spuInfo.id!)
    saleAttrList.value = result
  } catch (error) {
    ElMessage.error('获取销售属性失败,请重试')
  }
}
// 获取图片列表
const spuImageList = ref<SpuImageModel[]>([])
const getSpuImageListBySpuId = async () => {
  try {
    let result = await spuApi.getSpuImageListBySpuId(props.spuInfo.id!)
    spuImageList.value = result
  } catch (error) {
    ElMessage.error('获取图片列表失败,请重试')
  }
}

// 初始化数据
const initData = () => {
  getAttrList()   // 获取平台属性
  getSaleAttrListBySkuId()   // 获取销售属性列表
  getSpuImageListBySpuId()   // 获取图片列表数据
}

onMounted(() => {
  initData();
})

</script>

<style scoped>

</style>